<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="isUpdate ? t('action.edit') : t('action.create')"
    @ok="handleSubmit"
    :okText="t('action.save')"
    defaultFullscreen
  >
    <BasicForm @register="registerForm">
      <template #itemsSlot>
        <JVxeTable
          ref="itemsTableRef"
          :columns="itemsSchema"
          toolbar
          :toolbarConfig="toolbarConfig"
          resizable
          asyncRemove
          rowNumber
          :dataSource="itemsDataSource"
          @value-change="valueChange"
        >
          <template #toolbarSuffix>
            <div style="display: flex">
              <a-button type="primary" @click="handleOpen">选择商品</a-button>
              <!-- <a-input-group compact> -->
              <a-input
                ref="spCodeRef"
                v-model:value="spCode"
                placeholder="请扫描商品编号/条形码"
                @keydown.enter="enterAddNewRow"
                style="width: calc(100% - 80px)"
              />

              <a-tooltip title="请扫描商品编号/条形码">
                <a-button type="primary" @click="enterAddNewRow">
                  <template #icon><SearchOutlined /></template>
                  录入
                </a-button>
              </a-tooltip>
              <a-button type="primary" @click="handleOpenPur">选择采购订单</a-button>
              <!-- </a-input-group> -->
            </div>
          </template>
          <template #tableAction="props">
            <!-- <a-divider type="vertical" /> -->
            <Popconfirm title="确定删除吗？" @confirm="onDeleteItemsRow(props)">
              <a>{{ t('action.delete') }}</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </template>
      <template #action="{ record }">
        <TableAction :actions="itemsRowAction(record)" />
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button type="primary" @click="saveAndNext" :disabled="loading">{{ t('action.saveAndNext') }}</a-button>
    </template>
  </BasicModal>

  <SkuModel @register="register" />
  <ScanModel @register="scanRegister" />
  <PurModel @register="purRegister" />
</template>
<script lang="ts" setup>
  import { provide, ref, unref } from 'vue';
  import { Popconfirm } from 'ant-design-vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner, useModal } from '@/components/Modal';
  import { JVxeLinkageConfig, JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
  import { formSchema, itemsSchema } from './purchasePreBill.data';
  import { saveOrUpdate, getById,  } from './purchasePreBill.api';
  import {queryByText} from '/@/views/goods/sku/sku.api';
  import SkuModel from '/@/views/goods/sku/components/SkuModel.vue';
  import ScanModel from '/@/views/goods/sku/components/ScanModel.vue';
  import PurModel from './components/PurModel.vue';

  defineOptions({ name: 'PurchasePreBillModal' });
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const loading = ref(true);
  const toolbarConfig = {
    btn: ['remove'],
  };

  const [register, { openModal }] = useModal();
  const [scanRegister, { openModal: scanOpenModal }] = useModal();
  const [purRegister, { openModal: purOpenModal }] = useModal();

  const spCodeRef = ref(null);
  const spCode = ref<string>();

  const itemsTableRef = ref<JVxeTableInstance>();
  const itemsDataSource = ref<any[]>([]);
  const [registerForm, { getFieldsValue, setFieldsValue, resetFields, validate, getFormValue, submit }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: { span: 23 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    itemsDataSource.value = [];
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate) || data?.isCopy) {
      setFieldsValue({ ...data?.record });
      //回显子表数据
      const result = await getById({ id: data?.record?.id });
      if (result && result.items) {
        result.items.map((item) => {
          item.skuId = item.id;
          item.id = '';
        });
      }
      itemsDataSource.value = result?.items || [];
    }
  });

  /**
   * 打卡弹出框
   */
  function handleOpen() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function itemsRowAction(record) {
    return [
      {
        label: t('action.delete'),
        onClick: handleItemsEdit.bind(null, record),
      },
    ];
  }

  function handleItemsEdit(record) {
    console.log(record);
  }

  async function getItemsData() {
    let itemsDataValid = true;
    let itemsData: Recordable[] = [];
    if (!itemsDataValid) {
      throw { errorFields: [{ name: ['items'] }] };
    }
    itemsData = itemsTableRef.value!.getTableData();
    console.log('获取值:', { itemsData });
    return itemsData;
  }

  /**
   * 保存并继续
   */
  function saveAndNext() {
    handleSubmit(false);
  }

  /**
   * @param data 成功后是否关闭弹框,默认值:true
   */
  async function handleSubmit(data) {
    try {
      const values = await validate();
      values.items = await getItemsData();
      if (!isUpdate.value && values.items) {
        values.items.map((item) => {
          console.log('item:' + item);
          item.skuId = item.id;
          item.id = '';
        });
      }
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values, isUpdate.value);
      if (data) {
        closeModal();
      } else {
        resetFields();
      }
      emit('success');
      createMessage.success(t('common.saveSuccessText'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  const setSpCodeCursor = () => {
    setTimeout(() => {
      const cursorPosition = spCode.value?.length;
      spCodeRef.value?.focus();
      spCodeRef.value?.setSelectionRange(cursorPosition, cursorPosition);
    }, 500);
  };

  function insertData(rows) {
    rows.forEach((row) => {
      row.totalAmount = row.costPrice | 0;
      // row.totalAmount = (row.skuNum * row.costPrice) | 0;
    });
    // itemsTableRef.value.addRows(rows);
    itemsTableRef.value?.insertRows(rows);
    valueChange(null, true);
  }

  provide('insertData', insertData);

  async function onDeleteItemsRow({ row }) {
    // 调用删除方法
    const res = await itemsTableRef.value?.removeRows(row);
    if (res && res.rows.length > 0) {
      createMessage.success('删除成功');
    }
  }

  async function enterAddNewRow() {
    const param = { text: spCode.value, type: 'purchase' };
    const res = await queryByText(param);
    if (res.records?.length > 1) {
      scanOpenModal(true, {
        isUpdate: false,
        param,
      });
    } else {
      insertData(res.records);
    }
  }

  async function valueChange(e, f) {
    if (!f) {
      const { row } = e;
      row.totalAmount = (row.skuNum * row.costPrice) | 0;
    }
    let itemsData: Recordable[] = itemsTableRef.value!.getTableData();
    const totalAmount = itemsData.reduce((sum, item) => sum + (item.totalAmount | 0), 0);
    setFieldsValue({ totalAmount: totalAmount });
    //表单验`visitor来访人员`通过后获取的值
    let fields = await validate(['discountAmount']);
    setFieldsValue({ discountLastAmount: totalAmount - (fields.discountAmount || 0) });
    setSpCodeCursor();
  }

  function handleOpenPur() {
    purOpenModal(true, {
      isUpdate: false,
    });
  }

  async function insertDataPur(rows) {
    if (rows.length > 0) {
      const record = rows[0];
      setFieldsValue({ ...record });
      //回显子表数据
      const result = await getById({ id: record?.id });
      if (result && result.items) {
        result.items.map((item) => {
          item.skuId = item.id;
          item.id = '';
        });
      }
      itemsDataSource.value = result?.items || [];
    }
  }

  provide('insertDataPur', insertDataPur);
</script>

<style lang="less" scoped>
  :root {
    --panel-left: 0;
    --panel-top: 0;
  }
  :deep(.vxe-grid .vxe-pulldown--panel) {
    position: fixed;
    // // z-index: 9999 !important;
    left: var(--panel-left);
    top: var(--panel-top);
  }
  .dropdown-warp {
    width: 600px;
    height: 300px;
  }
</style>
